package com.xuantian.baoming.util;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class UserAgentUtil {

    //获取移动端系统
    public static String getDeviceType(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");

        if (userAgent != null) {
            userAgent = userAgent.toLowerCase();

            if (userAgent.contains("android")) {
                return "Android";
            } else if (userAgent.contains("iphone") || userAgent.contains("ipad")) {
                return "iOS";
            } else if (userAgent.contains("mobile")) {
                return "WAP";
            }
        }

        return "Unknown";
    }
    //获取用户ip地址
    public static String getClientIp(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        return ipAddress;
    }

    /**
     * 获取微信openid
     * @param code
     * @return
     * @throws Exception
     */
    public static String getOpenId(String code) throws Exception {

        if (code == null){
            return null;
        }
        // 构建请求URL
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + "wx68daede909161799"
                + "&secret=" + "f656d7c2080a3977b7d89a6a2dc4f160"
                + "&code=" + code
                + "&grant_type=authorization_code";

        // 发送HTTP GET请求
        URL url = new URL(requestUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        int responseCode = connection.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) { // 请求成功
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                response.append(line);
            }
            in.close();
            // 解析JSON响应，获取openid
            String jsonResponse = response.toString();
            JsonObject jsonObject = new Gson().fromJson(jsonResponse, JsonObject.class);
            System.out.println("jsonObject=======>"+ jsonObject);
            String openid = jsonObject.get("openid").getAsString();
            System.out.println("openid=======>: " + openid);
            return openid;
        } else {
            throw new Exception("HTTP GET请求失败：" + responseCode);
        }
    }
}
